using System;
using System.IO;
using Castle.Model.Resource;

namespace BEGDC.Utility.Castle
{
	/// <summary>
	/// Summary description for EncryptFileResource.
	/// </summary>
	public class EncryptFileResource : AbstractStreamResource
	{
		private const string Key_Start = "<item key=\"hibernate.connection.connection_string\">";
		private const string Key_End = "</item>";

		public EncryptFileResource(string fileName)
		{
			string file = string.Empty;
			StreamReader filestr = null;
			try
			{
				filestr = new StreamReader(Path.Combine(AbstractResource.DefaultBasePath ,fileName));
				file = filestr.ReadToEnd();
				int index1 = file.IndexOf(Key_Start)+Key_Start.Length;
				int index2 = file.IndexOf(Key_End, index1);
				int len = index2 - index1 ;
				string constr = file.Substring(index1, len);
				string newconstr = BEGDC.Utility.Security.EncryptTool.Decrypt(constr, BEGDC.Utility.Configuration.ConfigConst.Key);
                file = file.Replace(constr, newconstr);
			}
			catch
			{
			}
			finally
			{
				if (filestr != null)
					filestr.Close();
			}
			byte[] bytes = System.Text.Encoding.UTF8.GetBytes(file);
			stream = new MemoryStream(bytes);
		}

		private Stream stream;
		protected override Stream Stream
		{
			get
			{
				return this.stream;
			}
		} 

		public override IResource CreateRelative(string resourceName)
		{
			return new EncryptFileResource(resourceName);
		}
	}
}
